package com.mago.tis.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.mago.tis.pojo.Tiscit;
import com.mago.tis.pojo.Tismct;
import com.mago.tis.pojo.Tistit;
import com.mago.tis.service.IChallanService;
import com.mago.tis.service.ICompanyService;
import com.mago.tis.service.ITraderService;
import com.mago.tis.service.ITransportService;
import com.mago.tis.serviceImpl.ChallanService;
import com.mago.tis.serviceImpl.CompanyService;
import com.mago.tis.serviceImpl.TraderService;
import com.mago.tis.serviceImpl.TransportService;
import com.mago.tis.utility.ApplicationConstant;
import com.mago.tis.utility.ApplicationException;
import com.mago.tis.utility.CollectionUtil;
import com.mago.tis.utility.DateUtil;
import com.mago.tis.utility.StringUtil;

/**
 * Controller that will handle all kind of Challans
 * 
 * @author Piyush
 * 
 */
public class ChallanController extends BaseController {
	private static final Logger logger = Logger
			.getLogger(ChallanController.class);
	private IChallanService challanService;
	private ITraderService traderService;
	private ITransportService transportService;

	public ChallanController() {
		challanService = new ChallanService();
		traderService = new TraderService();
		transportService = new TransportService();
	}

	public void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		logger.info("Challan controller started");
		String action = request.getParameter(ApplicationConstant.ACTION);
		String grossWeightTotal = request
				.getParameter(ApplicationConstant.GROSS_WEIGHT_TOTAL);
		String raBillNo = request
				.getParameter(ApplicationConstant.RA_BILL_NO);
		
		String netWeightTotal = request
				.getParameter(ApplicationConstant.NET_WEIGHT_TOTAL);
		
		String dateInString = request
				.getParameter(ApplicationConstant.DATE_IN_STRING);
		
		String resultingPage = "";

		// Action == First Challan
		if (StringUtil.isNullOrEmpty(action)
				&& ((action.equals(ApplicationConstant.FIRST_CHALLAN)) || ((action
						.equals(ApplicationConstant.SECOND_CHALLAN))))) {

			String ids = request.getParameter("challan1Ids");
			List<Tismct> dataList = null;
			try {
				dataList = challanService.loadChallan1Data(ids);
				if (!CollectionUtil.isEmptyList(dataList)) {
					Tismct tismct = (Tismct) dataList.get(0);
					String date = tismct.getVmsInDate();
					request.setAttribute("date",
							DateUtil.convertStringToDate(date));
				}
			} catch (ApplicationException e) {
				request.setAttribute("message", e);
			}

			request.setAttribute("data", dataList);
			request.setAttribute("dataList", dataList);

			if (action.equals(ApplicationConstant.FIRST_CHALLAN)) {
				List<Tistit> tradersList = new ArrayList<Tistit>();
				try {
					tradersList = traderService.getTraders();
					request.setAttribute("tradersList", tradersList);
				} catch (ApplicationException e) {
					logger.info("Exception in ChallanController service()--->"
							+ e);
					e.printStackTrace();
				} catch (Exception e) {
					logger.info("Exception in ChallanController service()--->"
							+ e);
					e.printStackTrace();
				}
				request.setAttribute("grossWeightTotal", grossWeightTotal);
				resultingPage = "pages/jsp/first-challan.jsp";
			} else if (action.equals(ApplicationConstant.SECOND_CHALLAN)) {
				String trader = request.getParameter("trader");
				if (StringUtil.isNullOrEmpty(trader)) {
					String[] traderArr = trader.split(",");
					request.setAttribute("trader", traderArr[1]);
					request.setAttribute("traderId", traderArr[0]);
					//long traderId=Long.parseLong(traderArr[0]);
					List<Tistit> tradersList = new ArrayList<Tistit>();
					try {
						tradersList = traderService.getTradersById(traderArr[0]);
						request.setAttribute("tradersList", tradersList);
					} catch (ApplicationException e) {
						logger.info("Exception in ChallanController second service()--->"
								+ e);
						e.printStackTrace();
					} catch (Exception e) {
						logger.info("Exception in ChallanController second service()--->"
								+ e);
						e.printStackTrace();
					}
										
					request.setAttribute("netWeightTotal", netWeightTotal);
					request.setAttribute("grossWeightTotal", grossWeightTotal);
					request.setAttribute("raBillNo", raBillNo);
					request.setAttribute("dateInString", dateInString);
					request.setAttribute("recordIds", ids);
					resultingPage = "pages/jsp/second-challan.jsp";
				}
			}

		} else if (StringUtil.isNullOrEmpty(action)
				&& action.equals(ApplicationConstant.THIRD_CHALLAN)) {
			String finalDifference = request
					.getParameter(ApplicationConstant.FINAL_DIFFERENCE);
			String traderId = request
					.getParameter(ApplicationConstant.TRADER_ID);
			String recordIds = request
					.getParameter(ApplicationConstant.RECORD_ID);
			String dateTOfrd = request.getParameter("dateTOfrd");
			List<Tistit> tradersList = new ArrayList<Tistit>();
			List<Tiscit> companyInfo = new ArrayList<Tiscit>();
			ICompanyService companyservice = new CompanyService();
			try {
				tradersList = traderService.getTradersById(traderId);
				companyInfo = companyservice.getCompanyInfoById("1");
				
			} catch (ApplicationException e) {
				logger.error("Exception in challan Controller THIRD_CHALLAN--->"
						+ e);
				e.printStackTrace();
			} catch (Exception e) {
				logger.error("Exception in challan Controller THIRD_CHALLAN--->"
						+ e);
				e.printStackTrace();
			}
			String transDispatchFrom="";
			String transDispatchTo="";
			String datePattern = "\\d{1,2}/\\d{1,2}/\\d{4}";
		    boolean isDate = dateInString.matches(datePattern);
		    if(StringUtil.isNullOrEmpty(dateInString) && isDate){
		    	String[] dateTOfrdArr = dateInString.split("/");
				transDispatchFrom="01-"+dateTOfrdArr[1]+"-"+dateTOfrdArr[2];
				
				int x=Integer.parseInt(dateTOfrdArr[1]);
				if ( x % 2 == 0 ){
					if(x==2)
						transDispatchTo="28-"+dateTOfrdArr[1]+"-"+dateTOfrdArr[2];
					else
						transDispatchTo="30-"+dateTOfrdArr[1]+"-"+dateTOfrdArr[2];
				}
				else
					transDispatchTo="31-"+dateTOfrdArr[1]+"-"+dateTOfrdArr[2];
		    }
		    
		      
			/*if(StringUtil.isNullOrEmpty(dateInString)){
				String[] dateTOfrdArr = dateTOfrd.split("-");
				transDispatchFrom="01-"+dateTOfrdArr[1]+"-"+dateTOfrdArr[0];
				
				int x=Integer.parseInt(dateTOfrdArr[1]);
				if ( x % 2 == 0 ){
					if(x==2)
						transDispatchTo="28-"+dateTOfrdArr[1]+"-"+dateTOfrdArr[0];
					else
						transDispatchTo="30-"+dateTOfrdArr[1]+"-"+dateTOfrdArr[0];
				}
				else
					transDispatchTo="31-"+dateTOfrdArr[1]+"-"+dateTOfrdArr[0];
			}*/
		    request.setAttribute("companyInfo", companyInfo);
			request.setAttribute("transDispatchFrom", transDispatchFrom);
			request.setAttribute("transDispatchTo", transDispatchTo);
			String challanIds = request.getParameter("challan2Ids");
			request.setAttribute("traderObj", tradersList);
			double roundOffGross = Math.round(Double.parseDouble(grossWeightTotal) * 100.0) / 100.0;
			request.setAttribute("grossWeightTotal", roundOffGross);
			double roundOffFinalDiff = Math.round(Double.parseDouble(finalDifference) * 100.0) / 100.0;
			request.setAttribute("finalDifference", roundOffFinalDiff);
			
			double roundOffNetWt = Math.round(Double.parseDouble(netWeightTotal) * 100.0) / 100.0;
			request.setAttribute("netWeightTotal", roundOffNetWt);
			
			request.setAttribute("raBillNo", raBillNo);
			request.setAttribute("dateInString", dateInString);
						
			request.setAttribute("challanIds", challanIds);
			request.setAttribute("recordIds", recordIds);
			resultingPage = "pages/jsp/third-challan.jsp";
		} else if (StringUtil.isNullOrEmpty(action)
				&& action.equals(ApplicationConstant.THIRD_CHALLAN_SAVE)) {
			String finalDifference = request
					.getParameter(ApplicationConstant.FINAL_DIFFERENCE);
			String traderId = request
					.getParameter(ApplicationConstant.TRADER_ID);
			String ids = request.getParameter(ApplicationConstant.BILLED_ID);
			String grandTotal = request
					.getParameter(ApplicationConstant.GRAND_TOTAL);
			String slipIds = request.getParameter(ApplicationConstant.SLIP_ID);
			try {
				boolean isUpdated = transportService
						.updateMasterDataStatusAfterBilling(ids);
				boolean isSaved = transportService
						.saveChallan(slipIds, traderId, finalDifference,
								grandTotal, netWeightTotal);
			} catch (ApplicationException e) {
				logger.error("Exception in THIRD_CHALLAN save--->"
						+ e.getMessage());
				e.printStackTrace();
			} catch (Exception e) {
				logger.error("Exception in challan THIRD_CHALLAN save--->"
						+ e.getMessage());
				e.printStackTrace();
			}
		}
		rd = request.getRequestDispatcher(resultingPage);
		rd.forward(request, response);
		logger.info("Challan controller ended");
	}

}
